package com.zero2oneit.mall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zero2oneit.mall.auth.config.WxAuthProperties;
import com.zero2oneit.mall.auth.feign.member.MemberLoginFeign;
import com.zero2oneit.mall.auth.utils.WXCore;
import com.zero2oneit.mall.common.bean.auth.WxAppletsAuth;
import com.zero2oneit.mall.common.utils.HttpUtils;
import com.zero2oneit.mall.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * Description:
 *
 * @author yjj
 * @date 2021/3/5 12:28
 */
@RestController
@RequestMapping("/unAuth/WxApplets")
public class WXAppletsAuthApi {

    @Autowired
    private WxAuthProperties wxAuthProperties;

    @Autowired
    private MemberLoginFeign memberLoginFegin;

    @RequestMapping(value = "/login")
    public R WxAppletsLogin(@RequestBody WxAppletsAuth wxAppletsAuth){
        String code = wxAppletsAuth.getCode();
        //微信那边的接口，grant_type=authorization_code是固定的
        //发送请求给微信后端
        JSONObject jsonObject= JSON.parseObject(HttpUtils.sendGet(wxAuthProperties.getUrl(), wxAuthProperties.getUrlParam()+code));
        //解密EncryptedData获取phoneNumber
        String decrypt = WXCore.decrypt(wxAuthProperties.getAppletId(), wxAppletsAuth.getEncryptedData(), jsonObject.getString("session_key"), wxAppletsAuth.getIv());
        Map map = JSON.parseObject(decrypt, Map.class);
        wxAppletsAuth.setMemberPhone(map.get("phoneNumber")+"");
        wxAppletsAuth.setWxOpenid(jsonObject.getString("openid"));
        return  memberLoginFegin.WxAppletsLogin(wxAppletsAuth);
    }
}
